package a.b.reggie.service.impl;

import a.b.reggie.mapper.AddressBookMapper;
import a.b.reggie.pojo.AddressBook;
import a.b.reggie.pojo.User;
import a.b.reggie.service.IAddressBookService;
import a.b.reggie.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class IAddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    private IUserService userService;

    /**
     * 添加地址
     * @param phone
     * @param addressBook
     */
    @Transactional
    public void saveOne(Long phone,AddressBook addressBook) {
        //通过电话查找用户id
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        Long userId = user.getId();

        addressBook.setUserId(userId);
        this.save(addressBook);
    }

    /**
     * 修改默认地址
     * @param id
     */
    @Transactional
    public void setDefault(Long id) {

        //将原默认地址改为普通地址
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook one = this.getOne(queryWrapper);
        if (one!=null){
            one.setIsDefault(0);
            this.updateById(one);
        }

        //根据id查询对应地址并设置为默认地址
        AddressBook byId = this.getById(id);
        byId.setIsDefault(1);
        this.updateById(byId);
    }

    /**
     * 获取默认地址
     */
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDefault,1);
        return this.getOne(queryWrapper);
    }
}
